package com.dragon.www.haier.popupwindow;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.PopupWindow;

import com.dragon.www.haier.R;
import com.dragon.www.haier.adapter.RoomAdapter;
import com.dragon.www.haier.database.DataHelper;
import com.dragon.www.haier.entity.Room;
import com.dragon.www.haier.fragment.FirstScreenFragment;
import com.dragon.www.haier.util.CameraUtil;
import com.dragon.www.haier.util.CameraUtilOverKitkat;
import com.dragon.www.haier.util.Config;
import com.dragon.www.haier.view.dialog.RoomEditDialog;

import java.util.HashMap;
import java.util.List;

/**
 * Created by 51268 on 2016/3/14.
 */
public class RoomPopWindow implements AdapterView.OnItemClickListener {
    public static final int PHOTO_REQUEST_GALLERY = 1;// 从相册中选择
    /*
   房间popwindow
    */
    private PopupWindow popupWindowRoom;

    /*
    房间popwindow上的返回
     */
    private Button buttonBackRoom;
    private Button buttonEditRoom;
    private Button buttonDeleteRoom;
    private Button buttonChangeRoom;
    /*
    上下文
     */
    private FirstScreenFragment mFirstScreenFragment;

    /*
    此popwindow相对于哪一个view的偏移量，确定popwindow的位置，单位px
     */
    private View view;
    private int xOffsetToView;
    private int yOffsetToView;
    private int mPosition;
    /*
    popwindow的大小，单位px
     */
    private int widthPx;
    private int heightPx;
    private List<Room> mRooms ;
    private RoomAdapter adapter;
    private GridView gview;

    private boolean bRoomEditMode = false;
    private HashMap<String, Object> mHasIntoEditModeMap = new HashMap<String, Object>();

    // room新增编辑对话框
    private RoomEditDialog mRoomEditDialog;

    public RoomPopWindow(FirstScreenFragment fragment, List<Room> rooms, int widthPx, int heightPx, View v, int xOffsetToView, int yOffsetToView) {
        mFirstScreenFragment = fragment;
        view = v;
        this.mRooms = rooms;
        this.heightPx = heightPx;
        this.widthPx = widthPx;
        this.xOffsetToView = xOffsetToView;
        this.yOffsetToView = yOffsetToView;
    }

    public void showPopWindow() {
        View contentView = LayoutInflater.from(mFirstScreenFragment.getContext()).inflate(R.layout.room_view, null);
        buttonBackRoom = (Button) contentView.findViewById(R.id.bt_back);
        buttonEditRoom = (Button) contentView.findViewById(R.id.bt_edit);
        buttonDeleteRoom = (Button) contentView.findViewById(R.id.bt_delete);
        buttonChangeRoom = (Button) contentView.findViewById(R.id.bt_change);
        popupWindowRoom = new PopupWindow(contentView, widthPx, heightPx, true);
        popupWindowRoom.showAsDropDown(view, xOffsetToView, yOffsetToView);
        popupWindowRoom.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        gview = (GridView) contentView.findViewById(R.id.gview);
        adapter = new RoomAdapter(mFirstScreenFragment.getContext());
        gview.setOnItemClickListener(this);

        gview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mFirstScreenFragment.getContext());
                final String[] options = {"添加背景图片"};
                builder.setItems(options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        switch (which) {
                            case 0:
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                    mPosition = position;
                                    CameraUtilOverKitkat.selectPic(mFirstScreenFragment.getActivity(), PHOTO_REQUEST_GALLERY);
                                } else {
                                    CameraUtil.gotoAlbumView(mFirstScreenFragment.getActivity(), PHOTO_REQUEST_GALLERY);
                                }

                                break;

                            default:
                                break;
                        }
                    }
                });
                builder.show();
                return true;
            }
        });
        gview.setAdapter(adapter);

        buttonBackRoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bRoomEditMode) {
                    //退出编辑模式
                    bRoomEditMode = false;
                    mHasIntoEditModeMap.clear();
                    buttonEditRoom.setVisibility(View.VISIBLE);
                    buttonDeleteRoom.setVisibility(View.GONE);
                    buttonChangeRoom.setVisibility(View.GONE);
                    buttonBackRoom.setText("返回");
                    refreshData();
                } else {
                    //退出房间管理窗口
                    mFirstScreenFragment.showMainView();
                    if (popupWindowRoom != null) {
                        popupWindowRoom.dismiss();
                    }
                }
            }
        });
        buttonEditRoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //进入编辑模式
                bRoomEditMode = true;
                buttonEditRoom.setVisibility(View.GONE);
                buttonDeleteRoom.setVisibility(View.GONE);
                buttonChangeRoom.setVisibility(View.GONE);
                buttonBackRoom.setText("取消");
                refreshData();
            }
        });
        buttonDeleteRoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bRoomEditMode) {
                    //删除房间 并 退出编辑模式
                    for (String key : mHasIntoEditModeMap.keySet()) {
                        int deletePosition = Integer.valueOf((String) mHasIntoEditModeMap.get(key)).intValue();
                        int deleteRoomId = mRooms.get(deletePosition).getRoomid();
                        DataHelper.getInstance().deleteRoom(deleteRoomId);
                        DataHelper.getInstance().deleteDevice(deleteRoomId);
                        if (Config.getRoomId() == deleteRoomId) {

                        }
                    }
                    bRoomEditMode = false;
                    mHasIntoEditModeMap.clear();
                    buttonEditRoom.setVisibility(View.VISIBLE);
                    buttonDeleteRoom.setVisibility(View.GONE);
                    buttonChangeRoom.setVisibility(View.GONE);
                    buttonBackRoom.setText("返回");
                    refreshData();
                }
            }
        });
        buttonChangeRoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bRoomEditMode) {
                    //修改房间 并 退出编辑模式
                    for (String key : mHasIntoEditModeMap.keySet()) {
                        int changePosition = Integer.valueOf((String) mHasIntoEditModeMap.get(key)).intValue();
                        Room changeRoom = mRooms.get(changePosition);
                        showAddRoomDialog(changeRoom);
                    }
                    bRoomEditMode = false;
                    mHasIntoEditModeMap.clear();
                    buttonEditRoom.setVisibility(View.VISIBLE);
                    buttonDeleteRoom.setVisibility(View.GONE);
                    buttonChangeRoom.setVisibility(View.GONE);
                    buttonBackRoom.setText("返回");
                    refreshData();
                }
            }
        });
        refreshData();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (!bRoomEditMode) {
//            //如果在非编辑模式执行切换房间的操作
//            if (position == mRooms.size() - 1) {
//                showAddRoomDialog(null);
//            }
//            // 选中房间,退出popwindow,更新主画面房间信息
//            else {
                mFirstScreenFragment.showMainView();
                mFirstScreenFragment.selectRoom(mRooms.get(position));
                if (popupWindowRoom != null) {
                    popupWindowRoom.dismiss();
                }
            //}
        } else {
            // 如果在编辑模式的话执行选中删除操作
            if (position < mRooms.size() - 1) {
                if (mHasIntoEditModeMap.containsKey(String.valueOf(position))) {
                    mHasIntoEditModeMap.remove(String.valueOf(position));
                } else {
                    mHasIntoEditModeMap.put(String.valueOf(position), String.valueOf(position));
                }
                //根据不同的
                if (mHasIntoEditModeMap.size() > 1) {
                    buttonDeleteRoom.setVisibility(View.VISIBLE);
                    buttonChangeRoom.setVisibility(View.GONE);
                } else if (mHasIntoEditModeMap.size() == 1) {
                    buttonDeleteRoom.setVisibility(View.VISIBLE);
                    buttonChangeRoom.setVisibility(View.VISIBLE);
                } else if (mHasIntoEditModeMap.size() < 1) {
                    buttonDeleteRoom.setVisibility(View.VISIBLE);
                    buttonChangeRoom.setVisibility(View.GONE);
                }
                refreshData();
            }
        }
    }

    public void refreshData() {
        if(mRooms!=null){
            adapter.setRoomEditEnable(bRoomEditMode);
            adapter.setRoomEditMap(mHasIntoEditModeMap);
            adapter.setData(mRooms);
        }
    }

    public void showAddRoomDialog(final Room room) {
        mRoomEditDialog = new RoomEditDialog(mFirstScreenFragment.getActivity());
        mRoomEditDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mRoomEditDialog.setRoom(room);
        mRoomEditDialog.setLisntener(new RoomEditDialog.OnSelectListener() {
            @Override
            public void addPhoto() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    CameraUtilOverKitkat.selectPic(mFirstScreenFragment.getActivity(), PHOTO_REQUEST_GALLERY);
                } else {
                    CameraUtil.gotoAlbumView(mFirstScreenFragment.getActivity(), PHOTO_REQUEST_GALLERY);
                }
            }

            @Override
            public void ok() {
                refreshData();
            }

            @Override
            public void cancel() {

            }
        });
        mRoomEditDialog.show();
    }

    public void setFilePath(Uri uri) {
//        if (mRoomEditDialog != null) {
//            mRoomEditDialog.setRoomImageAtButton(uri);
//        }
//        ImageLoader.getInstance().displayImage(uri, iv_add_photo );
//        room.setImgPath(uri.toString());
        mRooms.get(mPosition).setImgPath(uri.toString());
        SharedPreferences sharedPreferences = mFirstScreenFragment.getContext().getSharedPreferences("itcastPreference", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(String.valueOf(mRooms.get(mPosition).getRoomid()), uri.toString());
        editor.commit();
        refreshData();
    }
}
